package cn.bluech.template.ui

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import cn.bluech.lib.http.RxTransformer
import cn.bluech.template.R
import cn.bluech.template.ui.base.BaseActivity
import cn.bluech.template.webserver.HttpModel
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import java.io.IOException

/**
 * Description:
 * Create by Codeant on 2019/3/13.
 */
class WebServerActivity : BaseActivity(), View.OnClickListener {
    @JvmField
    var msgTv: TextView? = null
    @JvmField
    var regBtn: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webserver)
        regBtn!!.setOnClickListener(this)
    }

    override fun onClick(view: View) {
        regBtn!!.isEnabled = false
        HttpModel.getInstance()
                .api
                .home()
                .compose(RxTransformer.io2Main())
                .subscribe(object : Observer<ResponseBody> {
                    override fun onSubscribe(d: Disposable) {
                        Log.d(TAG, "onSubscribe")
                        msgTv!!.text = "onSubscribe"
                    }

                    override fun onNext(responseBody: ResponseBody) {
                        Log.d(TAG, "onNext")
                        try {
                            msgTv!!.text = responseBody.string()
                        } catch (e: IOException) {
                            e.printStackTrace()
                            msgTv!!.text = responseBody.toString()
                        }
                    }

                    override fun onError(e: Throwable) {
                        Log.d(TAG, "onError")
                        msgTv!!.text = e.message
                        regBtn!!.isEnabled = true
                    }

                    override fun onComplete() {
                        Log.d(TAG, "onComplete")
                        regBtn!!.isEnabled = true
                    }
                })
    }

    companion object {
        private val TAG = WebServerActivity::class.java.simpleName
    }
}